package com.it.data_queue.double_queue;

import java.util.Iterator;

/**
 * 基于双向环形链表实现
 *
 * @author: Coke
 * @DateTime: 2023/06/17/18:37
 **/
public class LinkedListDeque<E> implements Deque<E>, Iterable<E> {
    
    int capacity;
    int size;
    Node<E> sentinel = new Node<>(null, null, null);
    
    public LinkedListDeque (int capacity) {
        this.capacity = capacity;
        sentinel.next = sentinel;
        sentinel.prev = sentinel;
    }
    
    @Override
    public boolean officeFirst (E e) {
        if (isFull()) {
            return false;
        }
        Node<E> a = sentinel;
        Node<E> b = sentinel.next;
        Node<E> eNode = new Node<>(a, e, b);
        a.next = eNode;
        b.prev = eNode;
        size++;
        return true;
    }
    
    @Override
    public boolean officeLast (E e) {
        if (isFull()) {
            return false;
        }
        Node<E> a = sentinel.prev;
        Node<E> b = sentinel;
        Node<E> eNode = new Node<>(a, e, b);
        a.next = eNode;
        b.prev = eNode;
        size++;
        return true;
    }
    
    @Override
    public E pollFirst () {
        if (isFull()) {
            return null;
        }
        Node<E> a = sentinel;
        Node<E> removed = a.next;
        Node<E> b = removed.next;
        a.next = b;
        b.prev = a;
        size--;
        return removed.value;
    }
    
    @Override
    public E pollLast () {
        if (isFull()) {
            return null;
        }
        Node<E> b = sentinel;
        Node<E> removed = b.prev;
        Node<E> a = removed.prev;
        a.next = b;
        b.prev = a;
        size--;
        return removed.value;
    }
    
    @Override
    public E peekFirst () {
        if (isFull()) {
            return null;
        }
        return sentinel.next.value;
    }
    
    @Override
    public E peekLast () {
        if (isFull()) {
            return null;
        }
        return sentinel.prev.value;
    }
    
    @Override
    public boolean isEmpty () {
        return size == 0;
    }
    
    @Override
    public boolean isFull () {
        return size == capacity;
    }
    
    @Override
    public Iterator<E> iterator () {
        return new Iterator<E>() {
            Node<E> p = sentinel.next;
            
            @Override
            public boolean hasNext () {
                return p != sentinel;
            }
            
            @Override
            public E next () {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }
    
    
    static class Node<E> {
        Node<E> prev;
        E value;
        Node<E> next;
        
        public Node (Node<E> prev, E value, Node<E> next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }
}
